/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pl.gda.pg;

import java.util.Scanner;

/**
 *
 * @author M. Zawadzki
 */
public class TextUtils {
    private static Scanner scanner = new Scanner(System.in);

    /**
     * Displays message and reads line of text
     * 
     * @param message
     *            message to display
     * @return line of text
     */
    public static String readLine(String message) {
        System.out.print(message + ": ");
        return scanner.nextLine();
    }

    /**
     * Displays message and reads option
     * 
     * @return option selected
     */
    public static int readOption() {
        String line = readLine("Your choice");
        int value = -1;

        try {
            value = Integer.parseInt(line);
        } catch (NumberFormatException e) {
            // Do nothing
        }

        return value;
    }

    /**
     * Displays menu with given caption and a set of options
     * 
     * @param caption
     *            caption to display
     * @param options
     *            set of options
     * @return option selected
     */
    public static int showMenu(String caption, String... options) {
        int option;
        int len = options.length;
        int i = 1;

        System.out.println(caption + "\n");

        for (String entry : options)
            System.out.println(String.format("%2d) %s", i++, entry));

        System.out.println(String.format("\n%2d) %s", 0, "Exit\n"));

        do {
            option = readOption();

            if ((option < 0) || (option > len))
                System.out.println("Please select valid option: 0-" + len);
            else
                break;
        } while (true);

        if (option == 0) {
            DBUtils.disconnect();
            System.out.println("Bye!");
            System.exit(0);
        }

        return option;
    }
}
